package net.cyue.homework.student.management.filter;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.cyue.homework.student.management.util.ResponseUtil;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class RequestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("RequestFilter init");
        String contextPath = filterConfig.getServletContext().getContextPath();
        ResponseUtil.setContextPath(contextPath);
    }

    @Override
    public void doFilter(
        ServletRequest request,
        ServletResponse response,
        FilterChain chain
    ) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Cache-Control", "no-cache");

        System.out.print(httpServletRequest.getRemoteAddr());
        System.out.print(":");
        System.out.print(httpServletRequest.getRemotePort());
        System.out.print(" 请求 ");
        System.out.println(httpServletRequest.getRequestURI());
        chain.doFilter(httpServletRequest, response);
    }
}


